from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.db.models import F
from .models import Analysis


# 统计 我这个网站 所有界面的 访问量总和
class MD(MiddlewareMixin):
    def process_request(self, request):
        # 将数据库中的值+1
        try:
            a = Analysis.objects.filter(id=1).update(count=F("count") + 1)
            # a = Analysis.objects.get(id=1)
            # a.count = a.count+1
            # a.save()
            print(a)
        except Exception as e:
            Analysis.objects.create(count=1)
            print(e)

        print("md1  process_request 方法。", id(request))  # 在视图之前执行
        # return HttpResponse("本网站正在维护")

    def process_response(self, request, response):
        # 基于请求响应
        print("md1  process_response 方法！", id(request))  # 在视图之后
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("md1  process_view 方法！", id(request))  # 在视图之前执行 顺序执行
        print(view_func.__name__)
        # return view_func(request)

    # 有异常的时候会走
    def process_exception(self, request, exception):  # 引发错误 才会触发这个方法
        print("md1  process_exception 方法！", id(request))
        return HttpResponse(exception)  # 返回错误信息

    #
    def process_template_response(self, request, response):
        print("md1  process_template_response 方法！", id(request))
        return response


class MD2(MiddlewareMixin):
    def process_request(self, request):
        print("md2  process_request 方法。", id(request))  # 在视图之前执行

    def process_response(self, request, response):
        # 基于请求响应
        print("md2  process_response 方法！", id(request))  # 在视图之后
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("md2  process_view 方法！", id(request))  # 在视图之前执行 顺序执行
        print(view_func.__name__)
